package com.itcaius.weblog.web.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Caius
 * @description
 * @since Created in 2025-06-13
 */
public class MarkdownStatusUtil {

    private static final int WORDS_READ_PRE_MINUTE =  300;

    /**
     * 计算 markdown 字数
     * @param markdown
     * @return
     */
    public static int calculateWordCount(String markdown) {
        // 将空白字符字符（空格，制表符,换行符）替换为一个空格
        String cleanText = markdown.replaceAll("\\s+", "");
        // 匹配中文
        Pattern chinesePattern = Pattern.compile("[\\u4e00-\\u9fa5]");
        Matcher chineseMatcher = chinesePattern.matcher(cleanText);

        // 计算中文字数
        int chineseCount = 0;
        while (chineseMatcher.find()) {
            chineseCount++;
        }

        // 去除计算过的中文
        String textWithoutChinese = cleanText.replaceAll("[\\u4e00-\\u9fa5]", " ");

        if (StringUtils.isBlank(textWithoutChinese)) return chineseCount;

        // 使用空格分割文本为单词
        String[] words = textWithoutChinese.trim().split("\\s+");
        return chineseCount + words.length;
    }

    /**
     * 计算阅读时长
     * @param wordCount
     * @return
     */
    public static String calculateReadingTime(int wordCount) {
        if (wordCount >= WORDS_READ_PRE_MINUTE) {
            int minutes = wordCount / WORDS_READ_PRE_MINUTE;
            return "约 " + minutes + " 分钟";
        }
        int seconds = (wordCount % WORDS_READ_PRE_MINUTE) * 60 / WORDS_READ_PRE_MINUTE;

        if (seconds == 0) seconds = 1;

        return "约 " + seconds + " 秒";
    }
}
